package com.example.back.Controller;

import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.example.back.Annotation.PassToken;
import com.example.back.Entity.User;
import com.example.back.Repository.UserRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
/*
    登陆与注册的接口

 */
@Slf4j
@RestController
@RequestMapping("api")
public class ApiController {
    @Autowired
    private UserRepository userRepository;

    //登录接口，采用token验证
    @PassToken
    @PostMapping("/login")
    public Object login(@RequestBody User user) {
        JSONObject returnJson = new JSONObject();
        String userName = user.getUserName();
        User dataBaseUser = userRepository.findUserByUserName(userName);
        if (dataBaseUser == null) {
            returnJson.put("message", "未查询到用户或用户不存在");
            return returnJson;
        } else {
            if (!dataBaseUser.getUserPassword().equals(user.getUserPassword())) {
                returnJson.put("message", "密码错误");
                return returnJson;
            } else {
                //判断当前账号是否被上锁
                if (dataBaseUser.getLockedTimeStamp() + 3600000L > new Date().getTime()) {
                    returnJson.put("message", "账户仍在锁定，剩余：" + (new Date().getTime() - dataBaseUser.getLockedTimeStamp()) / 60000 + "分钟");
                    return returnJson;
                }
                //在这里生成token
                String token = JWT.create().withAudience(user.getUserName())
                        .sign(Algorithm.HMAC256(user.getUserPassword()));
                returnJson.put("token", token);
                returnJson.put("message", "登陆成功");
                dataBaseUser.setUserPassword("*");//不返回用户密码
                returnJson.put("user", dataBaseUser);
                return returnJson;
            }
        }
    }
    //注册接口
    @PassToken
    @PostMapping("/signup")
    public boolean signUp(@RequestBody User user) {
        try {
            user.setSignUpDate(new Date());
            userRepository.save(user);
        } catch (Exception e) {
            return false;
        }
        return true;
    }
}
